package ru.compscicenter.databases.zaikina.common.model;

import org.json.simple.JSONAware;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import java.io.*;

public class DocumentWithBody implements JSONAware, Cloneable {
    private final Document document;
    private String body = "";


    public DocumentWithBody(Document document) {
        this(document, "");
    }

    public DocumentWithBody(Document document, boolean loadBody) {
        this.document = document;
        if (loadBody) {
            try {
                load();
            } catch (IOException ex) {
                body = "";
            }
        }
    }

    public DocumentWithBody(Document document, String body) {
        this.document = document;
        this.body = body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public Document getDocument() {
        return document;
    }

    public String getBody() {
        return body;
    }

    public void write() throws IOException {
        BufferedWriter writer = new BufferedWriter(new FileWriter(document.getId().toString()));
        writer.write(body);
    }

    private void load() throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(document.getId().toString()));
        String line;
        while ((line = reader.readLine()) != null) {
            body += line;
        }
        reader.close();
    }

   public String toJSONString() {
        JSONObject obj = new JSONObject();
        obj.put("document", document);
        obj.put("body", body);
        return obj.toString();
    }

    public static DocumentWithBody parse(String jsonString) {
        String body;
        Document document;
        try {
            JSONObject obj = (JSONObject) JSONValue.parse(jsonString);
            body = obj.get("body").toString();
            document = Document.parse(obj.get("document").toString());
        } catch (Exception ex) {
            return null;
        }
        return new DocumentWithBody(document, body);
    }

    public DocumentWithBody clone() {
        Document documentCopy = document.clone();
        String bodyCopy = new String(body);
        return new DocumentWithBody(documentCopy, bodyCopy);
    }

     public boolean equals(Object obj) {
        if (obj instanceof DocumentWithBody) {
            DocumentWithBody doc = (DocumentWithBody) obj;
            return doc.document.equals(document) && doc.body.equals(body);
        }
        return false;
    }
}
